package com.example.demo.service;

import com.example.demo.dao.SysResourcesMapper;
import com.example.demo.dao.SysUserMapper;
import com.example.demo.pojo.sys.SysResources;
import com.example.demo.pojo.sys.SysRole;
import com.example.demo.pojo.sys.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserService implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysResourcesMapper sysResourcesMapper;

    public List<SysResources> getResources(String username) {
        List<SysResources> list = new ArrayList<>();
        SysUser sysUser = (SysUser) this.loadUserByUsername(username);
        //用户拥有的角色集合
        List<SysRole> sysRoles = sysUser.getSysRoles();
        //角色用户的权限集合
        sysRoles.forEach(sysRole -> {
            List<SysResources> sysResources =
                    sysResourcesMapper.loadResources(sysRole.getId());
            list.addAll(sysResources);
        });
        return list;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.loadUserByUsername(username);
        if(sysUser == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //设置用户拥有的角色集合
        sysUser.setSysRoles(sysUserMapper.loadRoles(sysUser.getId()));
        return sysUser;
    }
}
